#include "chatRoom.h"
#include <json-c/json.h>
#include "stdShared.h"

// 构造函数
ChatRoom::ChatRoom(const StdTcpSocketPtr &client) : m_clientInfo(client)
{
    // 数据库单例（todo...）
    // 连接数据库
    m_sqliteDB.connectDB("./music.db");

    // 创建数据库表
    // CREATE TABLE IF NOT EXISTS 如果表不存在就创建，存在就不创建
    // not null表示不允许用户名和密码为空
    const char *sql = "CREATE TABLE IF NOT EXISTS userInfo (username text not null, passwd text not null);";
    m_sqliteDB.executeSql(sql);
}

// 析构函数
ChatRoom::~ChatRoom()
{
}

// 判断用户是否存在
bool ChatRoom::userIsExist(const std::string &name)
{
    std::string sql = "select count(*) from userInfo where username = '" + name + "';"; // sqlite语句

    QueryResult res = m_sqliteDB.querySql(sql);
    if (res.rows[0][0] == "0")
    {
        return false;
    }

    return true;
}

// 保存用户信息
bool ChatRoom::saveUserInfo(const std::string &name, const std::string &passwd)
{
    // 格式化字符串
    const char *sql = "INSERT INTO userInfo (username, passwd) VALUES ('%s', '%s');"; // sqlite语句
    char requestSql[BUFFER_SIZE] = {0};
    sprintf(requestSql, sql, name.c_str(), passwd.c_str());

    // 执行sql语句
    return m_sqliteDB.executeSql(requestSql);
}

// 处理用户注册
void ChatRoom::handleRegisterInfo(const std::string &msg)
{
    // std::cout << "注册函数" << std::endl;
    // std::cout << "msg:" << msg << std::endl;

    // 1、将json字符串解析成json对象
    json_object *jsonObj = json_tokener_parse(msg.c_str());

    // 2、根据key得到value
    std::string name = json_object_get_string(json_object_object_get(jsonObj, "name"));
    std::string passwd = json_object_get_string(json_object_object_get(jsonObj, "passwd"));

    // 3、销毁json对象
    json_object_put(jsonObj);

    // 1、创建json对象
    json_object *resObj = json_object_new_object();

    // 2、向json对象添加<key, value>键值对
    json_object_object_add(resObj, "type", json_object_new_int(REGISTER));

    // 先判断用户是否存在
    if (userIsExist(name))
    {
        std::cout << name << " already exist." << std::endl;
        json_object_object_add(resObj, "status", json_object_new_int(REGISTER_EXIST_USER));
    }
    else
    {
        // std::cout << name << " not exist." << std::endl;

        // 不存在就保存用户信息
        saveUserInfo(name, passwd);
        json_object_object_add(resObj, "status", json_object_new_int(REGISTER_SUCCESS));
    }

    // 将json对象转为json字符串
    const char *resStr = json_object_to_json_string(resObj);

    // 发送回信息到客户端
    m_clientInfo->sendMessage(resStr);
}
// 处理用户登录
void ChatRoom::handleLoginInfo(const std::string &msg)
{
    std::cout << "登录函数" << std::endl;
    // std::cout << "msg:" << msg << std::endl;

    // 1、将json字符串解析成json对象
    json_object *jsonObj = json_tokener_parse(msg.c_str());

    // 2、根据key得到value
    std::string name = json_object_get_string(json_object_object_get(jsonObj, "name"));
    std::string passwd = json_object_get_string(json_object_object_get(jsonObj, "passwd"));

    // 3、销毁json对象
    json_object_put(jsonObj);

    // 1、创建json对象
    json_object *resObj = json_object_new_object();

    // 2、向json对象添加<key, value>键值对
    json_object_object_add(resObj, "type", json_object_new_int(LOGIN));

    // if (name == "zhangsan" && passwd == "456")
    // {
    //     json_object_object_add(resObj, "status", json_object_new_int(LOGIN_SUCCESS));
    // }
    // else
    // {
    //     json_object_object_add(resObj, "status", json_object_new_int(LOGIN_NOUSER));
    // }

    // 将json对象转为json字符串
    const char *resStr = json_object_to_json_string(resObj);

    // 发送回信息到客户端
    m_clientInfo->sendMessage(resStr);
}
